package com.example.backblog.controller.front.blog;

import com.example.backblog.controller.base.BaseController;
import com.example.backblog.dto.blog.CategoryDto;
import com.example.backblog.dto.blog.CategoryWithSizeDto;
import com.example.backblog.entity.blog.Category;
import com.example.backblog.repository.blog.BlogRepository;
import com.example.backblog.repository.blog.CategoryRepository;
import com.example.backblog.vo.ApiResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController("/category")
@RequestMapping("/category")
public class CategoryController extends BaseController<Category, CategoryDto, CategoryRepository> {
    @Autowired
    private BlogRepository blogRepository;
    @Autowired
    @Override
    public void setBaseRepository(CategoryRepository baseRepository) {

        this.baseRepository = baseRepository;
    }
    @GetMapping("/all/size")
    public ApiResult listAll(){
        List<Category> allCategory = this.baseRepository.findAll();
        List<CategoryWithSizeDto> categoryWithSizeDtos = new ArrayList<>();
        for (Category category : allCategory) {
            CategoryWithSizeDto categoryWithSizeDto = new CategoryWithSizeDto();
            BeanUtils.copyProperties(category,categoryWithSizeDto);
            Integer size = blogRepository.countAllByCategoryIdEquals(category.getId());
            categoryWithSizeDto.setSize(size);
            categoryWithSizeDtos.add(categoryWithSizeDto);
        }
        return ApiResult.success(categoryWithSizeDtos);
    }
}
